package org.daidai.abstrusewriting.homepage.live.networks;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class okHttp extends AbstactHttpUtils {
    private OkHttpClient httpUtils;
    public okHttp()
    {
        httpUtils=new OkHttpClient();
    }
    @Override
    public byte[] doGetData(String url) {
        byte []ret=null;
        if (url != null) {
            Request.Builder builder = new Request.Builder();
            Request request = builder.url(url).get().build();
            try {
               Response response = httpUtils.newCall(request).execute();
                if (response != null) {
                     ret=response.body().bytes();
                }
                response=null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    @Override
    public void doGetDataAsync(String url, final HttpTools tools) {
        byte ret[]=null;
        if (url != null) {
            Request.Builder builder = new Request.Builder();
            Request request = builder.url(url).get().build();
            httpUtils.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    int code = response.code();
                    if (code==200)
                    {
                        byte[] bytes = response.body().bytes();
                        if (bytes != null) {
                         tools.onSuccess(bytes);
                        }
                    }
                }
            });
        }
    }
}
